<template>
  <div class="shipment-up">
    <div class="mb-2 ml-4">
      <el-radio-group v-model="radio1" v-for="(item, index) in list" :key="item.kid">
        <el-radio :value="item.kid" size="large" @click="getkulist(index)">{{
          item.ku_name
        }}</el-radio>
      </el-radio-group>
    </div>
    <el-input v-model="input2" style="width: 240px;" placeholder="产品名称/类型/品牌/价格" :prefix-icon="Search"
                    @keyup.enter="search()" />
                <el-button @click="search()">点击查询</el-button>
    <el-descriptions title="产品列表" direction="vertical" :column="8" :size="size" border>
    

      <div v-for="(item, index) in tabLiset" :key="item.kid">
        <el-descriptions-item label="产品图片">
          <img :src="item.img" alt="" />
        </el-descriptions-item>
        <el-descriptions-item label="产品负责人">{{
          item.nickName
        }}</el-descriptions-item>
         <el-descriptions-item label="产品名称">{{
          item.name
        }}</el-descriptions-item>
        <el-descriptions-item label="产品品牌">{{
          item.type
        }}</el-descriptions-item>
        <el-descriptions-item label="产品单位">{{
          item.units
        }}</el-descriptions-item>
        <el-descriptions-item label="产品价格">￥{{ item.money }}</el-descriptions-item>
        <el-descriptions-item label="库存数量">{{
          item.amount
        }}</el-descriptions-item>

        <el-descriptions-item label="操作">
          
          
          <el-dialog
            v-model="dialogVisible[index]"
            title="入库"
            width="500"
          >
          <el-form :model="ruku">
      <el-form-item label="入库人" :label-width="formLabelWidth">
        <el-input v-model="ruku.nickName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="入库数量" :label-width="formLabelWidth">
        <el-input v-model="ruku.ruamount" autocomplete="off" />
      </el-form-item>
    </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogVisible[index] = false">取消</el-button>
                <el-button type="primary" @click="qvedingruku(index)">
                  确定
                </el-button>
              </div>
            </template>
          </el-dialog>
          
          <el-button plain @click="dialogVisible[index] = true">
            入库
          </el-button>


          
          <el-button plain @click="dialogFormVisible[index] = true">
            修改数据
          </el-button>
          <el-dialog v-model="dialogFormVisible[index]" title="修改数据" width="500">
            <el-form :model="forms[index]">
              <div class="text">
                <label class="text-box">修改图片</label>
                <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false"
                  :on-change="chooseImageFn">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
              <el-form-item label="产品名称" :label-width="formLabelWidth">
                <el-input v-model="forms[index].name" autocomplete="off" />
              </el-form-item>
              <el-form-item label="产品品牌" :label-width="formLabelWidth">
                <el-input v-model="forms[index].type" autocomplete="off" />
              </el-form-item>
              <el-form-item label="产品单位" :label-width="formLabelWidth">
                <el-input v-model="forms[index].units" autocomplete="off" />
              </el-form-item>
              <el-form-item label="产品价格" :label-width="formLabelWidth">
                <el-input v-model="forms[index].money" autocomplete="off" />
              </el-form-item>
              <el-form-item label="产品数量" :label-width="formLabelWidth">
                <el-input v-model="forms[index].newamount" autocomplete="off" />
              </el-form-item>
            </el-form>

            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogFormVisible[index] = false">取消</el-button>
                <el-button type="primary" @click="foot(index)">
                  确认
                </el-button>
              </div>
            </template>
          </el-dialog>
          <!-- 下 -->
          <el-button plain @click="showOutDialog(index)">
            出库
          </el-button>
          <el-dialog v-model="outerVisible[index]" title="出库确认" width="500">
            <el-form :model="forms[index]">
              <div class="text">
                <label class="text-box">商品图片</label>
                  <img  :src="forms[index].img" class="text-imgs" />
              </div>
              <el-form-item label="产品名称" :label-width="formLabelWidth">
                <el-input v-model="forms[index].name" autocomplete="off" />
              </el-form-item>
              <el-form-item label="产品品牌" :label-width="formLabelWidth">
                <el-input v-model="forms[index].type" autocomplete="off" />
              </el-form-item>
              <el-form-item label="产品单价" :label-width="formLabelWidth">
                <el-input v-model="forms[index].money" autocomplete="off" />
              </el-form-item>
              <el-form-item label="出货数量" :label-width="formLabelWidth">
                <el-input v-model="forms[index].newamount" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="closeOutDialog(index)"> <!-- 修改：添加了 closeOutDialog 方法 -->
                  取消
                </el-button>
                <el-button type="primary" @click="goku(index)"> <!-- 修改：添加了 confirmOut 方法 -->
                  确认
                </el-button>
              </div>
            </template>
            <el-dialog v-model="innerVisible[index]" title="请收好出货条形码" width="500" append-to-body> <!-- 修改：添加了 innerVisible 绑定 -->
             
              <canvas ref="barcodeCanvasRef" :id="'barcodeCanvas' + index"></canvas>

              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="closeInnerDialog(index)"> <!-- 修改：添加了 closeInnerDialog 方法 -->
                    取消
                  </el-button>
                  <el-button type="primary" @click="closeInnerDialog(index)"> <!-- 修改：添加了 confirmInner 方法 -->
                    确认
                  </el-button>
                </div>
              </template>
            </el-dialog>
          </el-dialog>
        </el-descriptions-item>
      </div>
    </el-descriptions>
  </div>

  <div class="kong"></div>
</template>

<script setup lang="ts">
import bwipjs from 'bwip-js';
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref, reactive ,nextTick} from "vue";
import {kuListall, kuListall01, alter, imggetup, ku_delete, amend_amount, search01,rukuApi } from "../../api/index";
import api from "../../api/request";
import {getTimenow} from "../../api/request";
import { ElMessage } from "element-plus";

const dialogFormVisible = ref<boolean[]>([]);
const dialogVisible = ref<boolean[]>([]);
const formLabelWidth = "140px";
const input2 = ref("");
const forms = reactive<any>({
  nickName: "",
  name: "",
  region: "",
  date1: "",
  img: "",
  id: "",
  delivery: false,
  type: '',
  resource: "",
  desc: "",
  amount: "",
  newamount:""
});


const ruku = reactive<any>({
  nickName: '',
  ruamount:''
});
//获取菠萝数据

// getTimenow("删除了列表")

const outerVisible = ref<boolean[]>([]);
const innerVisible = ref<boolean[]>([]);
const tabLiset = ref<any>([]);
const list = ref<any[]>([]);
const barcodeCanvasRef = ref<HTMLCanvasElement | null>(null);
const radio1 = ref("1");
const size = ref("");
const imageUrl = ref("");
const altimg = ref("");

type Item = {
  id: number;
  name: string;
  units: string;
  money: number;
  amount: number;
  type: string;
  img: string;
  kid: number;
  nickName: string;
};
// 新增方法：显示外层对话框
const showOutDialog = (index: number) => {
  outerVisible.value[index] = true;
};
// 新增方法：关闭外层对话框
const closeOutDialog = (index: number) => {
  outerVisible.value[index] = false;
};

// 新增方法：确认出库，显示内层对话框
const confirmOut = async (index: number) => {
  outerVisible.value[index] = false;
  innerVisible.value[index] = true;
  await nextTick()
  const canvasElement = document.getElementById(`barcodeCanvas${index}`) as HTMLCanvasElement;
  console.log(canvasElement);
  
  if (canvasElement) {
    bwipjs.toCanvas(canvasElement, {
      bcid: 'code128', // 条形码类型
      text: tabLiset.value[index].id.toString(),
      scale: 3, // 缩放比例
      height: 9, // 条形码高度
      width: 50,
      includetext: true, // 是否包括文本
      textxalign: 'center' // 文本对齐方式
    });
    getTimenow('出库成功')
  }
};

// 新增方法：关闭内层对话框
const closeInnerDialog = (index: number) => {
  innerVisible.value[index] = false;
};
//确认入库
const qvedingruku = async(index:any)=>{
  dialogVisible.value[index] =false
  let {nickName,ruamount} = ruku;
  let {amount,id} = forms[index];
  // console.log(nickName,ruamount,amount,id);
  let  newnum = Number(amount) + Number(ruamount);
  await rukuApi({newnum,id}).then(res=>{
   let {code} = res;
   if(code==200){
    ElMessage.success(`入库成功`)
    getTimenow(`入库${nickName}${ruamount}成功`)
   }else{
    ElMessage.error('入库失败')
   }
   }
  )
  
}

const goku = async (index: any) => {
  confirmOut(index)
  let { id ,amount ,name} = tabLiset.value[index];
  let  number  = JSON.parse(JSON.stringify(forms))
  // console.log(number);
  let { newamount } = number[index]
  let newamountNum = Number(newamount);
  let amountNum = Number(amount);
  // console.log(newamountNum,amountNum);
  if (newamountNum > amountNum) {
    ElMessage.error("出库数量大于库存");
    return;
  }

  let newnum = amountNum - newamountNum;
  // console.log(newnum);
  if (newnum <= 0) {
    //删除库存
    await ku_delete({ id })
    .then((res) => {
      if (res.code == 200) {
        console.log(name,amountNum);
        
        ElMessage.success(`出库${name}${amountNum}成功`)
      } else {
        ElMessage.error(res.msg)
      }
    })
  }else{
    //修改库存
    amend_amount({newnum,id})
  }
};
// 选择图片
const chooseImageFn = async (file: any) => {
  // console.log(file);
  if (file) {
    let fd = new FormData();
    fd.append("photo", file.raw);
    await imggetup(fd).then((res) => {
      if (res.code == 200) {
        forms.img = res.picUrl;
        imageUrl.value = api.url + res.picUrl;
        altimg.value = res.picUrl;
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

//获取仓库
const getkulist = (index: any) => {
  getTabList(index);
};
//搜索
const search =  async() => {
  let keyword = input2.value
  await search01({keyword})
  .then((res)=>{
    let { code, result } = res
    console.log(res);
    
    if (code == 200) {
      let Arr = result.map((item: any) => {
        return {
          nickName: item.nickName,
          id: item.id,
          name: item.name,
          units: item.units,
          money: item.money,
          amount: item.amount,
          type: item.type,
          img: api.url+item.img,
          kid: item.kid,
        }
        
      })
      console.log(Arr);
      
      tabLiset.value = Arr;
    }
    
  })
};
onMounted(() => {
  getList();
  getTabList(1);
  
});
//修改数据
const foot = async (index: number) => {
  dialogFormVisible.value[index] = false;
  // console.log(altimg.value);

  console.log(forms[index]);
  let { id,kid,name,units,money,newamount,type } = forms[index];
  let img = altimg.value;
  let amount =newamount 
  console.log(id,kid,name,units,money,newamount,type,img);
  await alter({ id,kid,name,units,money,amount,type,img }).then(
    (res) => {
      console.log(res);
      if (res.code == 200) {
        getTimenow('修改了库存信息')
        ElMessage.success('修改成功');
      }
    }
  );
};
// 获取仓库
const getList = async () => {
  await kuListall().then((res) => {
    let { code, result } = res;
    if (code == 200) {
      let arr = result.map((item: any) => ({
        ku_name: item.ku_name,
        kid: item.kid,
      }));
      list.value = arr;
    } else {
      console.log("失败");
    }
  });
};

// 获取表格数据
const getTabList = async (index: any) => {
  let kid = list.value[index]?.kid || "1";
  await kuListall01({ kid }).then((res) => {
    if (res.code == 200) {
      let { result } = res;
      console.log(result);
      let arr = result.map((item: Item) => ({
        id: item.id,
        name: item.name,
        units: item.units,
        money: item.money,
        amount: item.amount,
        type: item.type,
        img: api.url + item.img,
        kid: item.kid,
        nickName:item.nickName
      }));
      tabLiset.value = arr;
      // console.log(arr);

      // 初始化对话框状态和表单数据
      dialogFormVisible.value = new Array(arr.length).fill(false);
      outerVisible.value = new Array(arr.length).fill(false);
      innerVisible.value = new Array(arr.length).fill(false);
      for (let i = 0; i < arr.length; i++) {
        forms[i] = {
          id: arr[i].id,
          name: arr[i].name,
          units: arr[i].units,
          money: arr[i].money,
          newamount: arr[i].amount,
          amount: arr[i].amount,
          type: arr[i].type,
          kid: arr[i].kid,
          delivery: false,
          img: arr[i].img,
        };
      }
    } else {
      ElMessage.error(res.msg);
    }
  });
};
</script>

<style lang="less" scoped>
@import "../assets/less/public.less";

.el-button .is-plain {
  margin-left: 20px;
  margin-right: 20px;
}

.el-button {
  margin-left: 5px;
  margin-right: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  width: 100%;
  height: 100%;
  align-items: center;
}

.text {
  display: flex;
  justify-content: center;
  align-items: center;

  .text-box {
    margin-left: 70px;
  }
}

.avatar-uploader {
  width: 150px;
  height: 150px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;

  .avatar {
    width: 100%;
    height: 150px;
  }

  &:hover {
    border: 1px solid @bg;
  }
}

.el-radio-group {
  margin-right: 30px !important;
}
.text{
  .text-imgs{
    width: 150px;
    height: 150px;
    margin-left: 20px;
    margin-bottom: 20px
  }
}
.el-descriptions {
  margin-top: 20px;
  img{
    width: 60px;
  }
}

.kong {
  width: 100%;
  height: 60px;
}
</style>
